package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void save(Department department) {
        //检查参数合法性
        //假设业务很复杂
        departmentMapper.insert(department);
    }

    @Override
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
    }

    @Override
    public Department get(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Department> listAll() {
        return departmentMapper.selectAll();
    }


    @Override
    public PageInfo<Department> query(QueryObject qo) {
        //自己写的分页插件
        /*int count = departmentMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize()
                    , Collections.emptyList(), count);
        }
        //因为当删除最后一页最后一条数据时,页面任然返回的是,最后一页的,所以会导致页面无法显示,此时需要修改
        //判断实际页是否大于当前页数,是则重新赋值
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize() : count / qo.getPageSize() + 1;
        if (qo.getCurrentPage() > totalPage){
            qo.setCurrentPage(totalPage);
        }

        List<Department> departments = departmentMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), departments, count);

        */
        //工具的分页插件
        //可以点startPage,再点下载源码,就能看见中文注释
        //业务层控制器要跟着修改

        //开始分页(需要传入当前页,传入每一页显示数量),下一句
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //sql不要写limit,插件会自动在sql语句后面加上limit语句
        List<Department> departments = departmentMapper.selectForList(qo);
        return new PageInfo<>(departments);
    }


}
